package com.d3works.apps.base.web;

import com.d3works.apps.base.db.ImportConfiguration;
import com.d3works.apps.base.db.ImportHistory;
import com.d3works.apps.base.db.repo.ImportConfigurationRepository;
import com.d3works.apps.base.service.app.AppBaseService;
import com.d3works.apps.base.service.imports.ImportService;
import com.d3works.exception.service.TraceBackService;
import com.d3works.inject.Beans;
import com.d3works.meta.MetaFiles;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import com.google.inject.Singleton;
import java.io.File;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;

@Singleton
public class ImportConfigurationController {

  public void run(ActionRequest request, ActionResponse response) {

    ImportConfiguration importConfiguration =
        request.getContext().asType(ImportConfiguration.class);
    try {

      ImportHistory importHistory = Beans.get(ImportService.class).run(importConfiguration);

      response.setValue("statusSelect", ImportConfigurationRepository.STATUS_COMPLETED);
      response.setValue(
          "endDateTime", Beans.get(AppBaseService.class).getTodayDateTime().toLocalDateTime());

      response.setAttr("importHistoryList", "value:add", importHistory);
      File readFile = MetaFiles.getPath(importHistory.getLogMetaFile()).toFile();
      response.setNotify(
          FileUtils.readFileToString(readFile, StandardCharsets.UTF_8)
              .replaceAll("(\r\n|\n\r|\r|\n)", "<br />"));

    } catch (Exception e) {
      response.setValue("statusSelect", ImportConfigurationRepository.STATUS_ERROR);
      TraceBackService.trace(response, e);
    }
  }
}
